package jsyf.oa.service.report.reportCommon;

import com.alibaba.fastjson.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Repository;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import jsyf.com.util.FastJsonConvert;
import jsyf.oa.idao.BaseDao;
import jsyf.oa.ientity.IBaseEntity;
import jsyf.oa.service.wechat.service_company.HttpUtil;

/**
 * Created by jjx on 2018/4/22.
 */
@Repository
public class ReportCommonMethodsAndConstant extends BaseDao {

    private static final Logger LOG = Logger.getLogger(ReportCommonMethodsAndConstant.class);

    public static final int NUMBER_ZERO = 0;
    public static final int NUMBER_ONE = 1;
    public static final int NUMBER_TWO = 2;
    public static final int NUMBER_SIX = 6;
    public static final int NUMBER_SEVEN = 7;
    public static final int NUMBER_TEN = 10;
    public static final int NUMBER_ELEVEN = 11;
    public static final int NUMBER_TWELVE = 12;
    public static final int NUMBER_TWENTY_FOUR = 24;
    public static final int NUMBER_SIXTY = 60;
    public static final int NUMBER_ONE_THOUSAND = 1000;

    public Integer getWeekDay(String date) {
        //通过传过来的时间算出距周一的时间
        Date dayCurrent = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            dayCurrent = sdf.parse(date);
        } catch (Exception e) {
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(dayCurrent);
        int week = calendar.get(Calendar.DAY_OF_WEEK);
        if (week == NUMBER_ONE) {
            return NUMBER_SIX;
        } else {
            return week - NUMBER_TWO;
        }
    }


 /*   //判断app时间
    public String getIsApp(String isApp, String dateTime, String yesterday) {
        Calendar calendar = Calendar.getInstance();
        if (StringUtils.isNotBlank(isApp) && isApp.equals(NUMBER_ONE)) {
            boolean flag = DateUtils.isInDate(calendar.getTime(), WechatConstant.begiinFormat, WechatConstant.appMorningStart);
            if (flag) {
                dateTime = yesterday;
                return dateTime;
            } else {
                return dateTime;
            }
        } else {
            boolean flag = DateUtils.isInDate(calendar.getTime(), WechatConstant.begiinFormat, WechatConstant.noon);
            if (flag) {
                dateTime = yesterday;
                return dateTime;
            }
            return dateTime;
        }
    }*/

  /*  //判断电访时间（5点以前为昨日）
    public String getIsAppTelTargetTime(String isTelTarget, String dateTime, String yesterday) {
        Calendar calendar = Calendar.getInstance();
        if (StringUtils.isNotBlank(isTelTarget) && isTelTarget.equals("TEL_TARGET")) {
            boolean flag = DateUtils.isInDate(calendar.getTime(), WechatConstant.begiinFormat, WechatConstant.telTarget);
            if (flag) {
                dateTime = yesterday;
                return dateTime;
            } else {
                return dateTime;
            }
        } else {
            boolean flag = DateUtils.isInDate(calendar.getTime(), WechatConstant.begiinFormat, WechatConstant.noon);
            if (flag) {
                dateTime = yesterday;
                return dateTime;
            }
            return dateTime;
        }
    }*/

    //通过Id获取全部公司除了大客户
    public String getCompanysIdExceptDKHByUserId(String userId) {
        Set<String> company = new HashSet<>();
        StringBuffer sb = new StringBuffer();
        List<JSONObject> jsonList = null;
        //获取managerFlag = 1 (集团后台)的所有公司
        sb.append("SELECT DISTINCT(v_sys_user.companyId) FROM v_sys_user\n" +
                "WHERE v_sys_user.manageFlag =1 AND v_sys_user.id='" + userId + "' \n ");
        jsonList = super.queryForJsonList(sb.toString());
        sb.setLength(NUMBER_ZERO);
        for (JSONObject json : jsonList) {
            if (json.getString("companyId") != null && !json.getString("companyId").isEmpty()) {
                company.addAll(getComapnyIdExpectDKHByparentCompanyId(json.getString("companyId")));
            }
            //获取除了集团后台下公司的兼职的其他公司Id
            sb.append("SELECT DISTINCT(v_sys_user.companyId) ,t_sys_company.PARENT_ID AS parentId\n" +
                    " FROM v_sys_user LEFT JOIN t_sys_company on t_sys_company.id= v_sys_user.companyId \n" +
                    "WHERE t_sys_company.`NAME` not LIKE '%集团%' and  v_sys_user.id='" + userId + "'\n ");
            jsonList = super.queryForJsonList(sb.toString());
            sb.setLength(NUMBER_ZERO);
            for (JSONObject jsonObject : jsonList) {
                if (jsonObject.getString("parentId").equals(String.valueOf(NUMBER_ONE))) {
                    if (getComapnyIdExpectDKHByparentCompanyId(jsonObject.getString("companyId")) != null) {
                        company.addAll(getComapnyIdExpectDKHByparentCompanyId(jsonObject.getString("companyId")));
                    }
                } else {
                    company.add(jsonObject.getString("companyId"));
                }
            }
        }
        if (company.size() == 0) {
            return "''";
        }
        for (String companyId : company) {
            sb.append("'" + companyId + "',");
        }
        String sql = sb.toString();
        if (sql.endsWith(",")) {
            sql = sql.substring(NUMBER_ZERO, sql.length() - NUMBER_ONE);
        }
        //返回 'companyId','',''
        return sql;
    }

    //除了大客户
    public Set<String> getComapnyIdExpectDKHByparentCompanyId(String companysId) {
        String sql = "SELECT t_sys_company.ID AS companyId FROM t_sys_company WHERE  t_sys_company.del_flag = 0 and t_sys_company.name not like '%大客户%' and t_sys_company.PARENT_ID in('" + companysId + "')";
        List<JSONObject> jsonList = super.queryForJsonList(sql);
        Set<String> company = new HashSet<>();
        if (jsonList.size() != NUMBER_ZERO) {
            for (JSONObject json : jsonList) {
                String companyId = json.getString("companyId");
                if (companyId != null && !companyId.isEmpty()) {
                    company.add(companyId);
                } else {
                    return null;
                }
            }
        } else {
            company.add(companysId);
            return company;
        }
        return company;
    }

    public Date nowDate() {
        return super.getJdbcTemplate().queryForObject("select curdate();", Date.class);
    }

    public List<JSONObject> getEntryDate(List<JSONObject> listUser) {
        int dayNumber = 0;
        List<JSONObject> listSendData = new ArrayList<>();
        for (int i = 0; i < listUser.size(); i++) {
            JSONObject users = listUser.get(i);
            String entryDate = users.getString("entryDate");
            if (!StringUtils.isBlank(entryDate) && !"".equals(entryDate)) {
                try {
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    Date startDate = simpleDateFormat.parse(entryDate);
                    Date nowDate = nowDate();
                    Long aLong = nowDate.getTime() - startDate.getTime();
                    dayNumber = (int) (aLong / (NUMBER_ONE_THOUSAND * NUMBER_SIXTY * NUMBER_SIXTY * NUMBER_TWENTY_FOUR));
                    users.put("dayNumber", dayNumber);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            } else {
                users.put("dayNumber", NUMBER_ZERO);
            }
            listSendData.add(users);
        }
        return listSendData;
    }

/*    public String getYesterDay() {
        //通过传过来的时间算出前一天
        Date dayCurrent = super.getCurrentTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(dayCurrent);
        calendar.add(Calendar.DAY_OF_MONTH, -NUMBER_ONE);
        dayCurrent = calendar.getTime();
        return sdf.format(dayCurrent);
    }*/

    @Override
    public IBaseEntity convertJson2Entity(JSONObject json) {
        return null;
    }

    //通过Id获取大客户公司
    public String getDKHCompanysIdByUserId(String userId) {
        Set<String> company = new HashSet<>();
        StringBuffer sb = new StringBuffer();
        List<JSONObject> jsonList = null;
        //获取managerFlag = 1 (集团后台)的所有公司
        sb.append("SELECT DISTINCT(v_sys_user.companyId) FROM v_sys_user\n" +
                "WHERE v_sys_user.manageFlag =1 AND v_sys_user.id='" + userId + "'\n ");
        jsonList = super.queryForJsonList(sb.toString());
        sb.setLength(NUMBER_ZERO);
        for (JSONObject json : jsonList) {
            if (json.getString("companyId") != null && !json.getString("companyId").isEmpty()) {
                company.addAll(getDKHComapnyIdByparentCompanyId(json.getString("companyId")));
            }
            //获取除了集团后台下公司的兼职的其他公司Id
            sb.append("SELECT DISTINCT(v_sys_user.companyId) ,t_sys_company.PARENT_ID AS parentId\n" +
                    " FROM v_sys_user LEFT JOIN t_sys_company on t_sys_company.id= v_sys_user.companyId \n" +
                    "WHERE t_sys_company.`NAME` not LIKE '%集团%' and  v_sys_user.id='" + userId + "'\n ");
            jsonList = super.queryForJsonList(sb.toString());
            sb.setLength(NUMBER_ZERO);
            for (JSONObject jsonObject : jsonList) {
                if (jsonObject.getString("parentId").equals(String.valueOf(NUMBER_ONE))) {
                    if (getDKHComapnyIdByparentCompanyId(jsonObject.getString("companyId")) != null) {
                        company.addAll(getDKHComapnyIdByparentCompanyId(jsonObject.getString("companyId")));
                    }
                } else {
                    company.add(jsonObject.getString("companyId"));
                }
            }
        }
        if (company.size() == 0) {
            return "''";
        }
        for (String companyId : company) {
            sb.append("'" + companyId + "',");
        }
        String sql = sb.toString();
        if (sql.endsWith(",")) {
            sql = sql.substring(NUMBER_ZERO, sql.length() - NUMBER_ONE);
        }
        //返回 'companyId','',''
        return sql;
    }

    public Set<String> getDKHComapnyIdByparentCompanyId(String companysId) {
        String sql = "SELECT t_sys_company.ID AS companyId \n" +
                "FROM t_sys_company LEFT JOIN t_sys_depart  ON t_sys_depart.COMPANY_ID=t_sys_company.id\n" +
                "WHERE 1=1 and (t_sys_company.`NAME` LIKE '%大客户%' OR t_sys_depart.`NAME` LIKE '%大客户%')\n" +
                "AND t_sys_company.DEL_FLAG =0 and t_sys_depart.DEL_FLAG=0 AND t_sys_company.PARENT_ID in('" + companysId + "')\n" +
                "AND t_sys_company.PARENT_ID \n";
        List<JSONObject> jsonList = super.queryForJsonList(sql);
        Set<String> company = new HashSet<>();
        if (jsonList.size() != NUMBER_ZERO) {
            for (JSONObject json : jsonList) {
                String companyId = json.getString("companyId");
                if (companyId != null && !companyId.isEmpty()) {
                    company.add(companyId);
                } else {
                    return null;
                }
            }
        } else {
            company.add(companysId);
            return company;
        }
        return company;
    }

    //通过Id获取全部公司
    public String getAllCompanysIdByUserId(String userId) {
        Set<String> company = new HashSet<>();
        StringBuffer sb = new StringBuffer();
        List<JSONObject> jsonList = null;
        //获取managerFlag = 1 (集团后台)的所有公司
        sb.append("SELECT DISTINCT v_sys_user.companyId,v_sys_user.reportFlag  FROM v_sys_user\n" +
                "WHERE 1=1 AND v_sys_user.reportFlag=0 AND v_sys_user.id='" + userId + "'\n ");
        jsonList = super.queryForJsonList(sb.toString());
        //v_sys_user.manageFlag =1
        sb.setLength(NUMBER_ZERO);
        for (JSONObject json : jsonList) {
            if (!StringUtils.isBlank("companyId")&&!StringUtils.isBlank("manageFlag")) {
                company.add(json.getString("companyId"));
                company.addAll(getAllComapnyIdByparentCompanyId(json.getString("companyId")));
            }
            //获取除了集团后台下公司的兼职的其他公司Id
            sb.append("SELECT DISTINCT(v_sys_user.companyId) ,t_sys_company.PARENT_ID AS parentId\n" +
                    " FROM v_sys_user LEFT JOIN t_sys_company on t_sys_company.id= v_sys_user.companyId \n" +
                    "WHERE 1=1 and  v_sys_user.id='" + userId + "' \n ");
            jsonList = super.queryForJsonList(sb.toString());
            sb.setLength(NUMBER_ZERO);
            for (JSONObject jsonObject : jsonList) {
                if (jsonObject.getString("parentId").equals(String.valueOf(NUMBER_ONE))) {
                    if (getAllComapnyIdByparentCompanyId(jsonObject.getString("companyId")) != null) {
                        company.addAll(getAllComapnyIdByparentCompanyId(jsonObject.getString("companyId")));
                    }
                } else {
                    company.add(jsonObject.getString("companyId"));
                }
            }
        }
        if (company.size() == 0) {
            return "''";
        }
        for (String companyId : company) {
            sb.append("'" + companyId + "',");
        }
        String sql = sb.toString();
        if (sql.endsWith(",")) {
            sql = sql.substring(NUMBER_ZERO, sql.length() - NUMBER_ONE);
        }
        //返回 'companyId','',''
        return sql;
    }

    //获取父公司下全部公司
    public Set<String> getAllComapnyIdByparentCompanyId(String companysId) {
        String sql = "SELECT t_sys_company.ID AS companyId FROM t_sys_company WHERE  t_sys_company.del_flag = 0  and t_sys_company.PARENT_ID in('" + companysId + "')";
        List<JSONObject> jsonList = super.queryForJsonList(sql);
        Set<String> company = new HashSet<>();
        if (jsonList.size() != NUMBER_ZERO) {
            for (JSONObject json : jsonList) {
                String companyId = json.getString("companyId");
                if (companyId != null && !companyId.isEmpty()) {
                    company.add(companyId);
                } else {
                    return null;
                }
            }
        } else {
            company.add(companysId);
            return company;
        }
        return company;
    }


    //通过userId获取户公司除了滚滚向前
    public String getCompanysIdExceptByUserId(String userId) {
        Set<String> company = new HashSet<>();
        StringBuffer sb = new StringBuffer();
        List<JSONObject> jsonList = null;
        //获取managerFlag = 1 (集团后台)的所有公司
        sb.append("SELECT DISTINCT(v_sys_user.companyId) FROM v_sys_user\n" +
                "WHERE v_sys_user.manageFlag =1 AND v_sys_user.id='" + userId + "' \n ");
        jsonList = super.queryForJsonList(sb.toString());
        sb.setLength(NUMBER_ZERO);
        for (JSONObject json : jsonList) {
            if (json.getString("companyId") != null && !json.getString("companyId").isEmpty()) {
                company.addAll(getCompanysIdExceptByparentCompanyId(json.getString("companyId")));
            }
            //获取除了集团后台下公司的兼职的其他公司Id
            sb.append("SELECT DISTINCT(v_sys_user.companyId) ,t_sys_company.PARENT_ID AS parentId\n" +
                    " FROM v_sys_user LEFT JOIN t_sys_company on t_sys_company.id= v_sys_user.companyId \n" +
                    "WHERE t_sys_company.`NAME` not LIKE '%集团%' and  v_sys_user.id='" + userId + "'\n ");
            jsonList = super.queryForJsonList(sb.toString());
            sb.setLength(NUMBER_ZERO);
            for (JSONObject jsonObject : jsonList) {
                if (jsonObject.getString("parentId").equals(String.valueOf(NUMBER_ONE))) {
                    if (getCompanysIdExceptByparentCompanyId(jsonObject.getString("companyId")) != null) {
                        company.addAll(getCompanysIdExceptByparentCompanyId(jsonObject.getString("companyId")));
                    }
                } else {
                    company.add(jsonObject.getString("companyId"));
                }
            }
        }
        if (company.size() == 0) {
            return "''";
        }
        for (String companyId : company) {
            sb.append("'" + companyId + "',");
        }
        String sql = sb.toString();
        if (sql.endsWith(",")) {
            sql = sql.substring(NUMBER_ZERO, sql.length() - NUMBER_ONE);
        }
        //返回 'companyId','',''
        return sql;
    }

    //通过Id获取全部公司(有兼职总经理)
    public String getAllCompanysIdByUserIdPart(String userId) {
        Set<String> company = new HashSet<>();
        StringBuffer sb = new StringBuffer();
        List<JSONObject> jsonList = null;
        //获取managerFlag = 1 (集团后台)的所有公司
        sb.append("SELECT DISTINCT(v_sys_user.companyId) FROM v_sys_user\n" +
                "WHERE  v_sys_user.id='" + userId + "' \n ");
        jsonList = super.queryForJsonList(sb.toString());
        sb.setLength(NUMBER_ZERO);
        for (JSONObject json : jsonList) {
            if (json.getString("companyId") != null && !json.getString("companyId").isEmpty()) {
                company.add(json.getString("companyId"));
                company.addAll(getAllComapnyIdByparentCompanyId(json.getString("companyId")));
            }
            //获取除了集团后台下公司的兼职的其他公司Id
            sb.append("SELECT DISTINCT(v_sys_user.companyId) ,t_sys_company.PARENT_ID AS parentId\n" +
                    " FROM v_sys_user LEFT JOIN t_sys_company on t_sys_company.id= v_sys_user.companyId \n" +
                    "WHERE 1=1 and  v_sys_user.id='" + userId + "'\n ");
            jsonList = super.queryForJsonList(sb.toString());
            sb.setLength(NUMBER_ZERO);
            for (JSONObject jsonObject : jsonList) {
                if (jsonObject.getString("parentId").equals(String.valueOf(NUMBER_ONE))) {
                    if (getAllComapnyIdByparentCompanyId(jsonObject.getString("companyId")) != null) {
                        company.addAll(getAllComapnyIdByparentCompanyId(jsonObject.getString("companyId")));
                    }
                } else {
                    company.add(jsonObject.getString("companyId"));
                }
            }
        }
        for (String companyId : company) {
            sb.append("'" + companyId + "',");
        }
        String sql = sb.toString();
        if (sql.endsWith(",")) {
            sql = sql.substring(NUMBER_ZERO, sql.length() - NUMBER_ONE);
        }
        //返回 'companyId','',''
        return sql;
    }

    public Set<String> getCompanysIdExceptByparentCompanyId(String companysId) {
        String sql = "SELECT t_sys_company.ID AS companyId FROM t_sys_company WHERE  t_sys_company.del_flag = 0 " +
                "and t_sys_company.name not like '%集团%' and t_sys_company.PARENT_ID in('" + companysId + "')";
        List<JSONObject> jsonList = super.queryForJsonList(sql);
        Set<String> company = new HashSet<>();
        if (jsonList.size() != NUMBER_ZERO) {
            for (JSONObject json : jsonList) {
                String companyId = json.getString("companyId");
                if (companyId != null && !companyId.isEmpty()) {
                    company.add(companyId);
                } else {
                    return null;
                }
            }
        } else {
            company.add(companysId);
            return company;
        }
        return company;
    }

    /**
     * 通过经纬度获取距离(单位：米)
     *
     * @param lat1
     * @param lng1
     * @param lat2
     * @param lng2 *https://api.map.baidu.com/routematrix/v2/walking?output=json&origins=38.84124647,100.82616536&destinations=38.92687744140625,100.46052978515625&ak=PRiE4PRTzpiQUY4GrkwIDKLg2DYcfc5u&tactics=11
     * @return {"status":0,"result":[{"distance":{"text":"38.9公里","value":38911},"duration":{"text":"9.3小时","value":33347}}],"message":"成功"}
     */
    public String getDistanceByLatAndLng(double lat1, double lng1, double lat2, double lng2) {
        StringBuffer sb = new StringBuffer();
        sb.append("http://api.map.baidu.com/routematrix/v2/riding?");
        sb.append("output=json" + "&");
        sb.append("origins=" + lat1 + "," + lng1 + "&");
        sb.append("destinations=" + lat2 + "," + lng2 + "&");
        sb.append("ak=PRiE4PRTzpiQUY4GrkwIDKLg2DYcfc5u" + "&");
        sb.append("tactics=13");
        JSONObject jsonParams = HttpUtil.request(sb.toString(), "GET", null);
        if (jsonParams != null) {
            jsonParams = FastJsonConvert.convertJSONToObject(jsonParams, JSONObject.class);
            if (jsonParams.getString("status").equals("0")) {
                List<JSONObject> jsonList = FastJsonConvert.convertJSONToArray(jsonParams.getString("result"), JSONObject.class);
                return FastJsonConvert.convertJSONToObject(jsonList.get(0).getString("distance"), JSONObject.class).getString("text");
            }
        }else{
            LOG.info("签到与拜访差距(第一次请求): "+sb.toString()+" 返回:"+jsonParams);
            //重试一次
            jsonParams = HttpUtil.request(sb.toString(), "GET", null);
            if (jsonParams != null) {
                jsonParams = FastJsonConvert.convertJSONToObject(jsonParams, JSONObject.class);
                if (jsonParams.getString("status").equals("0")) {
                    List<JSONObject> jsonList = FastJsonConvert.convertJSONToArray(jsonParams.getString("result"), JSONObject.class);
                    return FastJsonConvert.convertJSONToObject(jsonList.get(0).getString("distance"), JSONObject.class).getString("text");
                }
            }else{
                LOG.info("签到与拜访差距(第二次请求): "+sb.toString()+" 返回:"+jsonParams);
            }

        }

        return "0公里";

    }


    //TEL_TARGET
    public String getYesterDayForTelTarget(String date) {
        Calendar calendar = Calendar.getInstance();
        if (date.length() == 10 && calendar.get(Calendar.HOUR_OF_DAY) <= 17) {
            //通过传过来的时间算出前一天
            Date dayCurrent = super.getCurrentTime();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            //今天是昨天
            if (sdf.format(dayCurrent).equals(date)) {
                calendar.setTime(dayCurrent);
                calendar.add(Calendar.DAY_OF_MONTH, -NUMBER_ONE);
                dayCurrent = calendar.getTime();
                return sdf.format(dayCurrent);
            } else {
                //昨天还是昨天
                return date;
            }
        } else {
            return date;
        }
    }
}
